package com.example.thymeleaf.service;

import com.example.thymeleaf.entity.User;
import org.springframework.stereotype.Indexed;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserService {
    private static Map<Integer, User> map=new HashMap<>();
    static {
        map.put(1,new User(1,"tomcat","tomcat@qq.com"));
        map.put(2,new User(2,"tom","tom@qq.com"));
        map.put(3,new User(3,"jerry","jerry@qq.com"));
        map.put(4,new User(4,"wqq","wqq@qq.com"));
        map.put(5,new User(5,"hxy","hxy@qq.com"));
    }

    public List<User> findAll(){
        List<User> list=new ArrayList<>();
        for (Map.Entry<Integer,User> entry : map.entrySet()){
            list.add(entry.getValue());
        }
        return list;
    }

    //根据id获取一行用户数据
    public Optional<User> findById(int id){
        return Optional.ofNullable(map.get(id));
    }

    public List<User> save(User user){
        List<User> list=new ArrayList<>();

        user.setId(map.size()+1);
        map.put(user.getId(),user);

        list.add(user);
        return list;
    }

    public List<User> delete(int id){
        List<User> list=new ArrayList<>();
        for (Map.Entry<Integer,User> entry : map.entrySet()){
            if (entry.getKey()==id){
                list.add(entry.getValue());
                map.remove(id);
                break;
            }
        }
        return list;
    }
}
